package com.abss.vote.controller;

import com.abss.vote.model.*;
import com.abss.vote.service.RedisService;
import com.abss.vote.service.UserBackstageService;
import com.abss.vote.service.UserReceptionService;
import com.abss.vote.util.*;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 *  前台
 */
@Controller
@CrossOrigin
@RequestMapping("/front")
public class UserReception {

    @Autowired
    private UserReceptionService userReceptionService;

    @Autowired
    RedisService redisService;

    @Autowired
    private MyProps myProps;

    /**
     * 定位到首页
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "redirect:/getActivityBySth";
    }

    @RequestMapping("/toupload")
    public String upload(){
        return "upload";
    }

    /**
     * 获取报名信息和作品信息
     * @param activity_id 活动ID
     * @param user_id 用户的唯一标识
     * @return
     */
    @ResponseBody
    @RequestMapping("/getRegInfoAndWorkInfo")
    public Map<String,Object> sign(int activity_id,String user_id){

        //通过ID查找活动详情
        //
        Map<String,Object> ret=new HashMap<String,Object>();
        UserRegInfo regInfo=userReceptionService.getUserRegInfo(user_id,activity_id);
        //查找报名信息
        ret.put("reg_info",regInfo);

        List<Work> works=userReceptionService.getWorksByUserIdAndActivityId(user_id,activity_id);
        //查找作品信息
        //这里作品用了复数  以防万一
        ret.put("work_info",works);

        ret.put("code",1);
        return ret;
    }

    /**
     * 微信端首页
     * @return
     */
    @RequestMapping("/sign")
    public String sign(int ACTIVITY_ID,Model model){
        model.addAttribute("ACTIVITY_ID",ACTIVITY_ID);
        return "front/sign-up";
    }

    @RequestMapping("/home")
    public String gotoHome(Model model,String admin,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        if(admin == null){
            if("100001".equals(mp.getSERVER_ID())){//主服务器
                admin = "feiyuebook";
            }else{//其他服务器，从logo中获取admin
                admin = userReceptionService.getAdmin(mp.getSERVER_ID());
            }
        }
        model.addAttribute("admin",admin);
        session.setAttribute("admin",admin);

        int res = userReceptionService.getProbation(mp.getSERVER_ID(),admin);
        if(res==1){
            return "front/probation";
        }


        //活动列表页面
        return "front/home";
    }
    //活动详情页
    @RequestMapping("/activity")
    public String gotoActivity(@RequestParam(value = "activity_id",required = false) String activity_id,Model model,HttpSession session,String admin){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        if(admin!=null){
            model.addAttribute("admin",admin);
        }

        int res = userReceptionService.getProbation(mp.getSERVER_ID(),admin);
        if(res==1){
            return "front/probation";
        }

        model.addAttribute("activity_id",activity_id);
        Activity activity = userReceptionService.getActivityId(Integer.parseInt(activity_id));
        activity.setACTIVITY_DETAILS(Utils.getHtml(activity.getACTIVITY_DETAILS()));
        List<DistrictList> districtInfo = userReceptionService.getCountyNoLook(activity.getSERVER_ID(),admin);
        model.addAttribute("dis",districtInfo);
        //获取该服务器的logo
        Logo logo = userReceptionService.getLogos(activity.getADMIN());
        model.addAttribute("logo",logo);
        //获取该活动是否显示获奖名单
        model.addAttribute("winners",activity.getWINNERS());
        model.addAttribute("activity",activity);


        return "front/activity_detail";
    }
    //活动详情页 初始用户信息
    @RequestMapping("/initUserInfo")
    public String initUserInfo(@ModelAttribute("user_info")User user,@ModelAttribute(value = "activity_id")String activity_id ,String admin,Model model){
        model.addAttribute("admin",admin);
        model.addAttribute("user_info",user);
        model.addAttribute("activity_id",activity_id);
        return "front/init_userinfo";
    }



    /**
     * 根据ID获取活动详细信息
     * 将该用户的投票表更新
     * @return
     */
    @RequestMapping("/getActivityId")
    public String getActivityId(int ACTIVITY_ID,int state, HttpSession session,Model model){
        Activity activity = userReceptionService.getActivityId(ACTIVITY_ID);//获取活动信息
        //设置报名人数
        activity.setWorkUserNum(redisService.getREG_USER(ACTIVITY_ID));
        List<DistrictListUserWorkVo> works = userReceptionService.getWorkByActivityId(ACTIVITY_ID);

        User user=(User) session.getAttribute("user");
        //更新用户投票信息
        user.setLEFT_VOTES(activity.getVOTES_LIMIT_PERDAY());//将活动中设置的每天点赞数量封装到user中
        user.setACTIVITY_ID(activity.getACTIVITY_ID());//将活动ID封装到user中
        int res = userReceptionService.updaUserVoteInfo(user);//判断用户是否在投票表中有信息，如果有就根据时间判断是否是今天投了票
        model.addAttribute("activity",activity);
        model.addAttribute("works",works);
        model.addAttribute("Name","");
        if(state==1){
            return "front/index";
        }
        return "front/active";
    }

    /**
     * 根据用户传过来的查询内容和活动ID查询作品信息
     *          此种作品不止一个
     * @param Name  查询的值
     * @param ACTIVITY_ID 作品ID
     * @return
     */
    @RequestMapping("/getWorkByUserName")
    public String  getWorkByUserName(String Name,int state, int ACTIVITY_ID, Model model,HttpSession session){
        Activity activity = userReceptionService.getActivityId(ACTIVITY_ID);//获取活动信息
        //设置报名人数
        int REG_USER= redisService.getREG_USER(ACTIVITY_ID);
        activity.setWorkUserNum(REG_USER);
        model.addAttribute("activity",activity);
        List<DistrictListUserWorkVo> workList = userReceptionService.getWorkByUserName(Name,ACTIVITY_ID);
        model.addAttribute("works",workList);
        model.addAttribute("Name",Name);
        User user=(User) session.getAttribute("user");
        user.setACTIVITY_ID(activity.getACTIVITY_ID());
        //更新用户投票信息
        user.setLEFT_VOTES(activity.getVOTES_LIMIT_PERDAY());//将活动中设置的每天点赞数量封装到user中
        user.setACTIVITY_ID(activity.getACTIVITY_ID());//将活动ID封装到user中
        int res = userReceptionService.updaUserVoteInfo(user);//判断用户是否在投票表中有信息，如果有就根据时间判断是否是今天投了票
        if(state==1){
            return "front/index";
        }
        return "front/active";
    }

    /**
     * 查询地址
     * @return
     */
    @RequestMapping("/getCounty")
    public List<DistrictList> getCounty(){
        return userReceptionService.getCounty();
    }

    /**
     * 发布作品时
     * 验证该手机号是否在此活动中被使用过
     * @return
     */
    @ResponseBody
    @RequestMapping("/verification")
    public String verification(String TELEPHONE,int ACTIVITY_ID){
        String msg="";
        int res = userReceptionService.verification(TELEPHONE,ACTIVITY_ID);
        if(res>0){//表里有此电话号
            msg="yes";
        }else{//表里无此电话号
            msg="no";
        }
        return msg;
    }

    /**
     * 发送短信验证码
     * @param tel
     * @return
     */
    @ResponseBody
    @RequestMapping("/getCode")
    public String getCode(String tel, HttpSession session){
        session.removeAttribute("code");//销毁之前验证码
        String msg="";
        int code = Utils.getRandom();//根据工具类创建验证码   此code就是验证码
        session.setAttribute("code",code);//将此短信验证码放进session中保存
        String result= SendCode.send(tel,code);
        if("success".equals(result)){//短信发送成功
            msg="1";
        }else{
            msg="0";
        }
        return msg;
    }


    public String checkCode(Integer code, HttpSession session){
        String msg="";
        Integer sessioncode = (Integer)session.getAttribute("code");
        if(sessioncode.equals(code)){//验证成功
            msg="success";
        }else{//验证失败
            msg="fail";
        }
        return msg;
    }



    /**
     * 报名
     * 当点击报名时，首先去查看是否已经报名，如果已经报名就从页面去修改
     * 如果没有报名就去报名
     * @param userWorkVo
     * @return
     */
    @RequestMapping("/singUp")
    public String signUp(UserWorkVo userWorkVo) {
        userWorkVo.setUSER_ID(userWorkVo.getUSER_ID());
        String msg="fail";
        int req = userReceptionService.singUp(userWorkVo);
        if(req>0){//上传成功
            msg="success";
        }
        return msg;
    }

    /**
     * 检查用户是否报名
     * @param ACTIVITY_ID
     */
    @RequestMapping("/checkSingUp")
    @ResponseBody
    public String checkSingUp(int ACTIVITY_ID,String user_id){
        String msg="fail";
        int res=userReceptionService.checkSingUp(ACTIVITY_ID,user_id);
        if(res>0){//该用户已经报名
            msg="success";
        }
        return msg;
    }

    /**
     * 用户已经报名，报名信息回显
     * @return
     */
    @RequestMapping("/getSingUp")
    @ResponseBody
    public UserWorkVo getSingUp(UserWorkVo userWorkVo){
        return userReceptionService.getSingUp(userWorkVo);
    }

    /**
     * 用户已经报名，修改信息
     * @return
     */
    @RequestMapping("/updateSingUp")
    public int updateSingUp(UserWorkVo userWorkVo){
        return userReceptionService.updateSingUp(userWorkVo);
    }


    /**
     * 设置浏览数，该活动下的每一个作品被浏览一次就添加一
     * @param ACTIVITY_ID
     * @return
     */
    @RequestMapping("/setVisist")
    public int setVisist(int ACTIVITY_ID){
        return userReceptionService.setVisist(ACTIVITY_ID);
    }

    /**
     * 设置投票数，该活动下的每一个作品被投票一次就添加一
     * @return
     */
    @RequestMapping("/vote")
    @ResponseBody
    public Map<String,Object> setVOTES(int activity_id,String user_id,int work_id){
        return userReceptionService.setVOTES(activity_id,user_id,work_id);
    }

    /**
     * 根据票数获取作品信息
     * @return
     */
    @RequestMapping("/getWorkByVotesNumber")
    public List<DistrictListUserWorkVo> getWorkByVotesNumber(){
        return userReceptionService.getWorkByVotesNumber();
    }

    /**
     * 根据作品ID获取作品详细信息
     * @param work_id
     * @return
     */
    @RequestMapping("/showWork")
    public String getWorkDetails(@ModelAttribute("user_info")User user,Integer work_id,Model model){
        Work work = userReceptionService.getWorkInfoById(work_id);
        //设置活动浏览数量
        redisService.setVisist(work.getACTIVITY_ID());
//        //设置作品浏览数量
        redisService.setWorkVisist(work.getACTIVITY_ID(),work_id);

        work.setWORK_VISIST(redisService.getWorkVisist(work.getACTIVITY_ID(),work_id));

        Activity activity=userReceptionService.getActivityId(work.getACTIVITY_ID());
        //设置报名人数
        int REG_USER= redisService.getREG_USER(work.getACTIVITY_ID());
        activity.setWorkUserNum(REG_USER);
        model.addAttribute("work",work);
        model.addAttribute("activity",activity);
        if(user!=null)
        model.addAttribute("user_info",user);
        return "front/player";
    }

    @ResponseBody
    @RequestMapping("/getActivities")
    public Map<String,Object> getActivities(@RequestParam(required=false,defaultValue="1")int start, @RequestParam(required=false,defaultValue="5")int count,String admin,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        String ServerId = mp.getSERVER_ID();//获取本服务器的编号，根据编号获取对应地区的活动
        List<Activity> activites = userReceptionService.getActivities(start,start+count-1,ServerId,admin);
        for(Activity ac:activites){
            //设置投票人数
            ac.setAutherNumber(redisService.getVotesUser(ac.getACTIVITY_ID()));
            //设置投票总数量
            ac.setVOTES_NUMBER(redisService.getVotesNumber(ac.getACTIVITY_ID()));
            //设置浏览数量
            ac.setACTIVITY_VISIST(redisService.getVisist(ac.getACTIVITY_ID()));
            //设置报名人数
            ac.setREG_USER(redisService.getREG_USER(ac.getACTIVITY_ID()));
        }
        Map<String,Object> ret=new HashMap<String,Object>();
        ret.put("code",1);
        ret.put("data",activites);
        return ret;
    }
    @ResponseBody
    @RequestMapping("/getActivityInfoById")
    public Map<String,Object> getActivityInfoById(int activity_id){

        Activity activity = userReceptionService.getActivityId(activity_id);//获取活动信息
        activity.setACTIVITY_DETAILS(Utils.getHtml(activity.getACTIVITY_DETAILS()));
        activity.setACTIVITY_VISIST(redisService.getVisist(activity.getACTIVITY_ID()));//设置浏览数量
        //设置报名人数
        int REG_USER= redisService.getREG_USER(activity.getACTIVITY_ID());
        activity.setWorkUserNum(REG_USER);
        activity.setVOTES_NUMBER(redisService.getVotesNumber(activity.getACTIVITY_ID()));
        Map<String,Object> ret=new HashMap<>();

        ret.put("data",activity);
        ret.put("code",1);
        return ret;
    }

    @ResponseBody
    @RequestMapping("/getWorksWithOrder")
    public  Map<String,Object> getWorksWithOrder(

            @RequestParam(required=false,defaultValue="")String search_content,
            @RequestParam(required=false,defaultValue="")String search_user_name,
            @RequestParam(required=false,defaultValue="0")Integer search_work_id,

            @RequestParam(required=false,defaultValue="0")int district_id,
            int activity_id,
            @RequestParam(required=false,defaultValue="1")int start,
            @RequestParam(required=false,defaultValue="5")int count,
            @RequestParam(required=false,defaultValue="0")int order_type

    ){
        //按 order_type 排序 查找指定范围的 作品
        List<Work> works=new ArrayList<>();
        int currentStage = userReceptionService.getCurrentStage(activity_id);
        if("".equals(search_content.trim()) && "".equals(search_user_name.trim()) && search_work_id==0 && district_id==0){
            works = userReceptionService.getWorksWithOrder(activity_id,start,start+count-1,order_type,currentStage);
        }else{
            works = userReceptionService.getWorksWithOrderAndSearch(search_user_name,search_work_id,district_id,search_content,activity_id,start,start+count-1,order_type,currentStage);
        }
        Map<String,Object> ret=new HashMap<String,Object>();
        ret.put("code",1);
        ret.put("data",works);
        return ret;
    }

    /**
     * @Description: 网页授权登录
     */
    @RequestMapping("/userLogin")
    public void wxScanLogin(HttpServletResponse response,String state){
        try {
            MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
            String addr=WxLogin.getcode(state,mp);
            //System.out.println("state>>>>"+state);
            response.sendRedirect(addr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/guide")
    public String guide(){
        return "front/guide";
    }

   // private static final String APP_ID = "wx1395f72209d8ddf4";
   // private static final String APP_SCRECT = "ed49850ab2db9e85334bbe37ef3e562e";

    /**
     * 网页授权登录回调
     */
    @RequestMapping("/wxCallBack")
    public String wxScanLoginCallBack(String code, String state, HttpServletResponse response,Model mo, RedirectAttributes model){
        try {
            //System.out.println("state:"+state);
            MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
            //获取token
            String token= HttpUtil.get(WxLogin.getoken(code,mp));

            userCallBack userCallBackToken = JsonUtil.jsonToObject(token, userCallBack.class);
            //获取信息
            String userInfo= HttpUtil.get(WxLogin.getuserinfo(userCallBackToken.getAccess_token(),userCallBackToken.getOpenid(),userCallBackToken.getLang()));
            userCallBack user = JsonUtil.jsonToObject(userInfo, userCallBack.class);
            //判断是否关注公众号(使用全局https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET获取的access_token)
//            String aeecss_token = WxShare.getAccess_token(APP_ID, APP_SCRECT);
//            String users=HttpUtil.get(WxLogin.getuse(aeecss_token,userCallBackToken.getOpenid()));
//            userCallBack usersq = JsonUtil.jsonToObject(users, userCallBack.class);
//            System.out.println("是否关注："+usersq.getSubscribe());
//            if(usersq.getSubscribe().equals("0")){//没有关注公众号
//                return "redirect:/front/guide";
//            }

            //将服务器信息添加到session中
            MpInfo mpInfo = userReceptionService.getMpInFo(myProps.getServerid());
//            try {
//                List<String> ls= FileUtils.getBanner();//获取配置文件中的数据
//                mpInfo.setSERVER_ID(ls.get(0));
//                mpInfo.setSERVER_NAME(ls.get(1));
//                mpInfo.setMP_APP_ID(ls.get(2));
//                mpInfo.setMP_APP_SECRET(ls.get(3));
//                mpInfo.setWXCALLBACK(ls.get(4));
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            user.setOpenid(mpInfo.getSERVER_ID()+"-"+user.getOpenid());
            //将用户信息添加数据库
            //判断是否添加过
            int res=userReceptionService.checkUser(user);
            //System.out.println("res"+res);
            if(res>0){//添加过    更改信息
                userReceptionService.updateUser(user);
            }else{//未添加过    直接填入
                userReceptionService.addUser(user);
            }
            User u =  userReceptionService.getUser(user.getOpenid());//根据用户ID获取用户信息
            //System.out.println("state>>>>"+state);
            String [] states = state.split("\\?");//[/front/showWork][work_id=255&user_id=200]
            if(states.length>=2){
                String [] kvps = states[1].split("&");//[work_id=255][user_id=200]
                for(String kvp : kvps) {
                    //System.out.println("kvp>>>>>"+kvp);
                    String[] kv = kvp.split("=");
                    if (kv.length == 2) {
                        model.addAttribute(kv[0], kv[1]);
                    }else if(kv.length == 3){
                        model.addAttribute(kv[0], kv[1]);
                        model.addAttribute("admin",kv[2]);
                    } else {
                        model.addAttribute(kv[0], "");
                    }
                }
            }

            //短暂保存
            model.addFlashAttribute("user_info",u);
            model.addFlashAttribute("wxCallback",true);
            //response.getWriter().print(u);
            return "redirect:"+states[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/front/activity";
    }



    /**
     * 删除用户信息
     * @param user_id
     * @param activity_id
     * @return
     */
    @ResponseBody
    @RequestMapping("/delUserRegInfo")
    public int delUserRegInfo(String user_id,int activity_id){
        int res = userReceptionService.delUser(user_id,activity_id);
        redisService.delREG_USER(activity_id);
        return res;
    }

    /**
     * 修改用户
     * @param userRegInfo
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateUserRegInfo")
    public int updUserRegInfo(UserRegInfo userRegInfo,HttpSession session){
        //System.out.println("提交的reginfo:"+userRegInfo);
        String sessioncode = session.getAttribute("code").toString();
        if(!sessioncode.equals(userRegInfo.getMESSAGE_CODE()) ){//验证成功
            return -1;
        }
        int res=0;
        userRegInfo.setMESSAGE_CODE(session.getAttribute("code").toString());

        if(userReceptionService.getUserRegInfo(userRegInfo.getUSER_ID(),userRegInfo.getACTIVITY_ID())!=null){
            return  userReceptionService.updUserRegInfo(userRegInfo);
        }else{
          res = userReceptionService.addUserRegInfo(userRegInfo);
          redisService.setREG_USER(userRegInfo.getACTIVITY_ID());
          return res;
        }

    }

    /**
     * 查询用户
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserRegInfo")
    public UserRegInfo getUserRegInfo(String user_id,int activity_id){
        return userReceptionService.getUserRegInfo(user_id,activity_id);
    }

    /**
     * 删除用户信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/delWork")
    public int delWork(int work_id){
        //System.out.println("删除作品》"+work_id);
        return userReceptionService.delWork(work_id);
    }



    /**
     * 上传音频
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/uploadSound")
    @ResponseBody
    public Map<String,Object> uploadSound(@RequestParam(value="file1",required = false) MultipartFile file1,@RequestParam(value="file2",required = false) MultipartFile file2,Work work){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Map<String,Object> ret=new HashMap<>();
        Encoder encoder = new Encoder();
        if(work.getWORK_ID()==null||"".equals(work.getWORK_ID())){
            //添加
            String Picture ="";
            String picName ="";
            if (file1.isEmpty()) {
                ret.put("code",-1);
                ret.put("msg","图片为空，请选择封面！");
                return ret;
            }
            long time1=Utils.getName();//获取当前时间戳
            String fileName1 = file1.getOriginalFilename();//获取原文件名
            Picture = "/copy/"+time1+ fileName1.substring(fileName1.indexOf("."));
            String name = time1+ fileName1.substring(fileName1.indexOf("."));
            File dest1 = new File(mp.getFILE_PATH() + Picture);
            try {
                file1.transferTo(dest1);
                picName = FileUtils.saveImage(dest1,name,mp);
            } catch (IOException e) {
                e.printStackTrace();
            }
            work.setWORK_IMGURL(picName);


            String Sound ="";
            if (file2.isEmpty()) {
                ret.put("code",-1);
                ret.put("msg","作品为空，请上传作品！");
                return ret;
            }
            //System.out.println(file2.getSize());
            if(file2.getSize()>(200*1024*1024)){
                ret.put("code",-1);
                ret.put("msg","请上传200M以内的作品！");
                return ret;
            }
            long ms = 0;
            long time2=Utils.getName();//获取当前时间戳
            String fileName2 = file2.getOriginalFilename();//获取原文件名
            Sound = "/sound/"+time2+( fileName2.indexOf(".")==-1?".mp3":fileName2.substring(fileName2.indexOf(".")));
            File dest2 = new File(mp.getFILE_PATH() + Sound);
            try {
                file2.transferTo(dest2);
                MultimediaInfo m = encoder.getInfo(dest2);
                ms = m.getDuration();
            } catch (Exception e) {
                e.printStackTrace();
            }
            int ss = 1000;

            Integer time=(int)(ms/ss) ;
            work.setWORK_LENTH(time);
            work.setRESOURCE_URL(mp.getDOMAIN_NAME()+Sound);
            work.setWORK_TYPE("1");
            int res = userReceptionService.addyinWork(work);
            redisService.addWork(work);
            ret.put("code",res);
            return ret;

        }else{
            //更新
            if(work.getWORK_IMGURL()==null||"".equals(work.getWORK_IMGURL())) {
                //System.out.println("音频图片修改");
                String Picture ="";
                String picName ="";
                if (file1.isEmpty()) {
                    ret.put("code",-1);
                    ret.put("msg","图片为空，请选择封面！");
                    return ret;
                }
                long time1=Utils.getName();//获取当前时间戳
                String fileName1 = file1.getOriginalFilename();//获取原文件名
                Picture = "/copy/"+time1+ fileName1.substring(fileName1.indexOf("."));
                String name = time1+ fileName1.substring(fileName1.indexOf("."));
                File dest1 = new File(mp.getFILE_PATH() + Picture);
                try {
                    file1.transferTo(dest1);
                    picName = FileUtils.saveImage(dest1,name,mp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                work.setWORK_IMGURL(picName);
            }
            if(work.getRESOURCE_URL()==null||"".equals(work.getRESOURCE_URL())) {
                //System.out.println("音频修改");
                long ms = 0;
//                String length= TimeLenght.ReadVideoTimeMs(file2);
                String Sound = "";
                if (file2.isEmpty()) {
                    ret.put("code",-1);
                    ret.put("msg","作品为空，请上传作品！");
                    return ret;
                }
                if(file2.getSize()>(200*1024*1024)){
                    ret.put("code",-1);
                    ret.put("msg","请上传200M以内的作品！");
                    return ret;
                }
                long time2 = Utils.getName();//获取当前时间戳
                String fileName2 = file2.getOriginalFilename();//获取原文件名
                Sound = "/sound/" + time2+( fileName2.indexOf(".")==-1?".mp3":fileName2.substring(fileName2.indexOf(".")));
                File dest2 = new File(mp.getFILE_PATH() + Sound);
                try {
                    file2.transferTo(dest2);
                    MultimediaInfo m = encoder.getInfo(dest2);
                    ms = m.getDuration();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int ss = 1000;

                Integer time=(int)(ms/ss) ;
                work.setWORK_LENTH(time);
                work.setRESOURCE_URL(mp.getDOMAIN_NAME()+Sound);
            }
            int res = userReceptionService.updSound(work);
            ret.put("code",res);
            return ret;
        }

    }
    /**
     * 上传图片
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/uploadPic")
    @ResponseBody
    public Map<String,Object> uploadPic(Work work){

        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        //获取最后更新时间
        Date last = mp.getLAST_UPDATE_TIME();
        //获取7200s前时间点
        Date two = Utils.gettwoDate();
//        if (last.before(two)) {//请求微信获取新信息
//            String aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());
//            String aeecss_ticket = WxShare.getAccess_ticket(aeecss_token);
//            //将数据存入数据库
//            mp.setACCESS_TOKEN(aeecss_token);
//            mp.setAEECSS_TICKET(aeecss_ticket);
//            userReceptionService.setMpInFo(mp);
//        }


        String aeecss_token=mp.getACCESS_TOKEN();
        if(last.before(two)){//请求微信获取新信息
            aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());

            //将数据存入数据库
            MpInfo mpInfo1=new MpInfo();
            mpInfo1.setACCESS_TOKEN(aeecss_token);
            mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
            mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
            userReceptionService.setMpInFo(mpInfo1);
            mp.setACCESS_TOKEN(aeecss_token);
        }








        Map<String,Object> ret=new HashMap<>();
        if(work.getWORK_ID()==null||work.getWORK_ID()==0){


            //设置封面
            work.setWORK_IMGURL(userReceptionService.getImageFromWeixin(work.getWORK_IMGURL(),mp));

            String[] work_arr=work.getRESOURCE_URL().split(",");
            List<String> work_list=new ArrayList<>();
            for (String aWork_arr : work_arr) {
                if (aWork_arr != null && !"".equals(aWork_arr))
                    work_list.add(userReceptionService.getImageFromWeixin(aWork_arr,mp));
            }
            //设置作品图片
            work.setRESOURCE_URL(String.join(",",work_list));


            work.setWORK_TYPE("2");
            int res = userReceptionService.addyinWork(work);
            redisService.addWork(work);
            ret.put("code",res);
            return ret;

        }else{
            //更新


            //设置封面
            if(!work.getWORK_IMGURL().startsWith("http"))
            work.setWORK_IMGURL(userReceptionService.getImageFromWeixin(work.getWORK_IMGURL(),mp));

            String[] work_arr=work.getRESOURCE_URL().split(",");
            List<String> work_list=new ArrayList<>();
            for (String work_item : work_arr) {
                if (work_item != null && !"".equals(work_item)){
                    if(!work_item.startsWith("http"))
                        work_list.add(userReceptionService.getImageFromWeixin(work_item,mp));
                    else
                        work_list.add(work_item);
                }
            }
            //设置作品图片
            work.setRESOURCE_URL(String.join(",",work_list));


            int res = userReceptionService.updSound(work);
            ret.put("code",res);
            return ret;
        }

    }

    /**
     * 修改视频
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/uploadVideo")
    @ResponseBody
    public Map<String,Object> updVideo(@RequestParam(value="file",required = false) MultipartFile file,Work work){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        //获取最后更新时间
        Date last = mp.getLAST_UPDATE_TIME();
        //获取7200s前时间点
        Date two = Utils.gettwoDate();
//        if (last.before(two)) {//请求微信获取新信息
//            String aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());
//            String aeecss_ticket = WxShare.getAccess_ticket(aeecss_token);
//            //将数据存入数据库
//            mp.setACCESS_TOKEN(aeecss_token);
//            mp.setAEECSS_TICKET(aeecss_ticket);
//            userReceptionService.setMpInFo(mp);
//        }

        String aeecss_token=mp.getACCESS_TOKEN();
        if(last.before(two)){//请求微信获取新信息
            aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());

            //将数据存入数据库
            MpInfo mpInfo1=new MpInfo();
            mpInfo1.setACCESS_TOKEN(aeecss_token);
            mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
            mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
            userReceptionService.setMpInFo(mpInfo1);
            mp.setACCESS_TOKEN(aeecss_token);
        }




        Map<String,Object> ret=new HashMap<>();
        Encoder encoder = new Encoder();
        if(work.getWORK_ID()==null||work.getWORK_ID()==0) {

            work.setWORK_IMGURL(userReceptionService.getImageFromWeixin(work.getWORK_IMGURL(),mp));

            String Video ="";

            long ms = 0;
            long time2=Utils.getName();//获取当前时间戳
            String fileName2 = file.getOriginalFilename();//获取原文件名

            Video = "/video/"+time2+( fileName2.indexOf(".")==-1?".mp4":fileName2.substring(fileName2.indexOf(".")));
            File dest2 = new File(mp.getFILE_PATH() + Video);
            try {
                file.transferTo(dest2);
                MultimediaInfo m = encoder.getInfo(dest2);
                ms = m.getDuration();
            } catch (Exception e) {
                e.printStackTrace();
            }
            int ss = 1000;

            Integer time=(int)(ms/ss) ;
            work.setWORK_LENTH(time);
            work.setWORK_TYPE("0");
            work.setRESOURCE_URL(mp.getDOMAIN_NAME()+Video);
            int res = userReceptionService.addyinWork(work);
            redisService.addWork(work);
            ret.put("code",res);
            return ret;
        }else{

            //设置封面
            if(!work.getWORK_IMGURL().startsWith("http"))
                work.setWORK_IMGURL(userReceptionService.getImageFromWeixin(work.getWORK_IMGURL(),mp));

            if(work.getRESOURCE_URL()==null||"".equals(work.getRESOURCE_URL())) {
//                System.out.println("视频修改");
                String length= TimeLenght.ReadVideoTimeMs(file);
                String Video = "";

                long ms = 0;
                long time2 = Utils.getName();//获取当前时间戳
                String fileName2 = file.getOriginalFilename();//获取原文件名
                Video = "/video/"+time2+( fileName2.indexOf(".")==-1?".mp4":fileName2.substring(fileName2.indexOf(".")));
                File dest2 = new File(mp.getFILE_PATH() + Video);
                try {
                    file.transferTo(dest2);
                    MultimediaInfo m = encoder.getInfo(dest2);
                    ms = m.getDuration();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int ss = 1000;

                Integer time=(int)(ms/ss) ;
                work.setWORK_LENTH(time);
                work.setRESOURCE_URL(mp.getDOMAIN_NAME()+Video);
            }

            int res = userReceptionService.updSound(work);
            ret.put("code",res);
            return ret;

        }

    }


    /**
     * 查询作品
     * @return
     */
    @ResponseBody
    @RequestMapping("/getWork")
    public Work getWork(int work_id){
        return userReceptionService.getWork(work_id);
    }

    //跳转页面
    @RequestMapping("/audioWorkUpload")
    public String gotoAudioWorkUpload(Integer activity_id,String user_id,Integer work_id ,Model model){

        Work work_info;
        if(work_id!=null){//编辑
            //编辑
            work_info= userReceptionService.getWorkInfoById(work_id);

        }else{
            //报名
            work_info=new Work();
            work_info.setACTIVITY_ID(activity_id);
            work_info.setUSER_ID(user_id);
        }
        model.addAttribute("work_info",work_info);

        return "front/upload_audio";
    }
    @RequestMapping("/videoWorkUpload")
    public String gotoVideoWorkUpload(Integer activity_id,String user_id,Integer work_id ,Model model){

        Work work_info;
        if(work_id!=null){//编辑
            //编辑
            work_info= userReceptionService.getWorkInfoById(work_id);

        }else{
            //报名
            work_info=new Work();
            work_info.setACTIVITY_ID(activity_id);
            work_info.setUSER_ID(user_id);
        }
        model.addAttribute("work_info",work_info);

        return "front/upload_video";
    }
    //跳转页面
    @RequestMapping("/pictureWork")
    public String pictureWork(Integer activity_id,String user_id,Integer work_id ,Model model){

        Work work_info;
        if(work_id!=null){//编辑
            //编辑
            work_info= userReceptionService.getWorkInfoById(work_id);
            model.addAttribute("is_back",1);
        }else{
            //报名
            work_info=new Work();
            work_info.setACTIVITY_ID(activity_id);
            work_info.setUSER_ID(user_id);
            model.addAttribute("is_back",0);
        }
        model.addAttribute("work_info",work_info);

        return "front/upload_pic";
    }

    //跳转页面
    @RequestMapping("/register")
    public String gotoRegister(int activity_id,String user_id,int is_edit,Model model,String admin){
        //System.out.println("user_id:"+user_id);

        UserRegInfo regInfo;
        if(is_edit==1){
            //编辑
            regInfo= userReceptionService.getUserRegInfo(user_id,activity_id);

        }else{
            //报名
            regInfo=new UserRegInfo();
            regInfo.setACTIVITY_ID(activity_id);
            regInfo.setUSER_ID(user_id);
        }
        //System.out.println("reginfo:"+regInfo);

        model.addAttribute("is_edit",is_edit);
        model.addAttribute("reg_info",regInfo);
        //获取该活动发布的服务器编号     如果是超级管理员发布的则查看除超级管理员之外的全部地址，如果是别人发布的则查看该服务器的地区
        Activity activity = userReceptionService.getActivityId(activity_id);
        List<DistrictList> districtInfo = userReceptionService.getCountyNoLook(activity.getSERVER_ID(),admin);
        model.addAttribute("district_info",districtInfo);
        return "front/register";
    }

    @RequestMapping("/readWork")
    public String readWork(int activity_id,String user_id,Model model){
        List<Article> articles = userReceptionService.getReadWork();
        for(Article ac:articles){
            ac.setACTIVITY_ID(activity_id);
            ac.setUSER_ID(user_id);
        }
        model.addAttribute("articles",articles);
        return "front/read";
    }

    @RequestMapping("/getActicleById")
    public String getActicleById(int ID,int activity_id,String user_id,Model model){
        Article article = userReceptionService.getActicleById(ID);
        article.setUSER_ID(user_id);
        article.setACTIVITY_ID(activity_id);
        model.addAttribute("article",article);
        return "front/record";
    }

    @ResponseBody
    @RequestMapping("/recordUpload")
    public String recordUpload(@RequestParam(value="file",required = false) MultipartFile file){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        String Sound ="";
        long time=Utils.getName();//获取当前时间戳
        String fileName = file.getOriginalFilename();//获取原文件名
        Sound = "/sound/"+time+( fileName.indexOf(".")==-1?"":fileName.substring(fileName.indexOf(".")));
        File dest = new File(mp.getFILE_PATH() + Sound);
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mp.getDOMAIN_NAME()+Sound;
    }

    //跳转页面
    @RequestMapping("/uploadRecorder")
    public String uploadRecorder(Work work ,Model model ,String WORK_LENTHs){
        work.setWORK_LENTH(Integer.parseInt(WORK_LENTHs)/1000);
        model.addAttribute("work_info",work);
        return "front/upload_record";
    }

    @ResponseBody
    @RequestMapping("/recorderWork")
    public int recorderWork(@RequestParam(value="file",required = false) MultipartFile file,Work work){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        String Picture ="";
        String picName ="";
        long time=Utils.getName();//获取当前时间戳
        String fileName = file.getOriginalFilename();//获取原文件名
        Picture = "/copy/"+time+ fileName.substring(fileName.indexOf("."));
        String name=time+ fileName.substring(fileName.indexOf("."));
        File dest = new File(mp.getFILE_PATH() + Picture);
        try {
            file.transferTo(dest);
            picName = FileUtils.saveImage(dest,name,mp);

        } catch (IOException e) {
            e.printStackTrace();
        }
        work.setWORK_IMGURL(picName);
        int res = userReceptionService.addRecorderWork(work);
        redisService.addWork(work);
        return res;
    }

    //跳转页面
    @RequestMapping("/PicLook")
    public String PicLook(int work_id,Model model){
        Work work = userReceptionService.getWorks(work_id);
        model.addAttribute("work",work);
        return "front/PicLook";
    }

    //跳转页面
    @RequestMapping("/PrizeLook")
    public String PrizeLook(int WORK_ID,int ACTIVITY_ID,Model model){
        PrizeUser prizeUser = userReceptionService.getWorksp(WORK_ID,ACTIVITY_ID);
        model.addAttribute("prizeUser",prizeUser);
        return "front/PrizeLook";
    }



    /**
     * 后台创建作品上传封面图
     * @param file1
     * @return
     */
    @ResponseBody
    @RequestMapping("/picUpload")
    public Map<String,Object> picUpload(@RequestParam(value = "file1", required = false) MultipartFile file1,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Map<String,Object> ret=new HashMap<>();
        String Picture ="";
        String picName ="";
        if (file1.isEmpty()) {
            ret.put("code",0);
            return ret;
        }
        long time1=Utils.getName();//获取当前时间戳
        String fileName1 = file1.getOriginalFilename();//获取原文件名
        Picture = "/copy/"+time1+ fileName1.substring(fileName1.indexOf("."));
        String name = time1+ fileName1.substring(fileName1.indexOf("."));
        File dest1 = new File(mp.getFILE_PATH() + Picture);
        try {
            file1.transferTo(dest1);
            picName = FileUtils.saveImage(dest1,name,mp);
            ret.put("code",1);
            ret.put("pic",picName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Autowired
    private UserBackstageService userBackstageService;


    @ResponseBody
    @RequestMapping("/getPrizes")
    public  Map<String,Object> getPrizes(int activity_id){
        List<Prize> prizes=userBackstageService.getPrizeListByActivityId(activity_id);
        Map<String,Object> ret=new HashMap<String,Object>();
        ret.put("code",1);
        ret.put("data",prizes);
        return ret;
    }

    @ResponseBody
    @RequestMapping("/getPrizeWorks")
    public  Map<String,Object> getPrizeWorks(int activity_id){
        List<Prize> prizes=userBackstageService.getPrizeWorkListByActivityId(activity_id);
        Map<String,Object> ret=new HashMap<String,Object>();
        ret.put("code",1);
        ret.put("data",prizes);
        return ret;
    }

}
